package io.github.wanggit.antrpc.console.web.filter;

import io.github.wanggit.antrpc.console.service.AccountService;
import io.github.wanggit.antrpc.console.web.constants.WebConstants;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class AuthFilter implements Filter {

    private AccountService accountService;

    private static Set<String> frees = new HashSet<>();

    static {
        frees.add("/378dc55768dd414eab98c5be96d3cad2/");
        frees.add("/login");
        frees.add("/login_submit");
        frees.add("/css/");
        frees.add("/fonts/");
        frees.add("/img/");
        frees.add("/js/");
        frees.add("/webfonts/");
        frees.add("/favicon.");
    }

    public AuthFilter(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(
            ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if (isFree(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Cookie[] cookies = httpServletRequest.getCookies();
            Cookie cookie = findCookie(cookies);
            boolean redirect = false;
            if (null == cookie) {
                redirect = true;
            } else {
                boolean success = accountService.checkToken(cookie.getValue());
                if (success) {
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    redirect = true;
                }
            }
            if (redirect) {
                ((HttpServletResponse) servletResponse).sendRedirect("/login");
            }
        }
    }

    @Override
    public void destroy() {}

    private Cookie findCookie(Cookie[] cookies) {
        if (null == cookies || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(), WebConstants.TOKEN)) {
                return cookie;
            }
        }
        return null;
    }

    private boolean isFree(String requestURI) {
        for (String free : frees) {
            if (requestURI.startsWith(free)) {
                return true;
            }
        }
        return false;
    }
}
